<template>
  <div style="position: relative">
    <template v-if="imgSize.verifyFloat">
      <el-popover
        popper-class="tw-login-verify-popper"
        placement="top"
        :width="imgSize.width"
        v-model="popVisible"
        trigger="hover">
        <div class="verify-img-out" :class="{xpopper: imgSize.verifyFloat}" :style="{'width': setSize.imgWidth, 'height': setSize.imgHeight}">
          <div class="verify-img-panel"
            :style="{'width': setSize.imgWidth, 'height': setSize.imgHeight, 'background-size' : setSize.imgWidth + ' '+ setSize.imgHeight}">
              <div class="verify-refresh" style="z-index:3" @click="refresh" v-show="showRefresh">
                <i class="el-icon-refresh"></i>
              </div>
              <img :src="'data:image/png;base64,' + pointBackImgBase" ref="canvas" alt=""  style="width:100%;height:100%;display:block"
              @click="bindingClick?canvasClick($event):undefined" v-show="pointBackImgBase">

              <div v-for="(tempPoint, index) in tempPoints" :key="index" class="point-area"
                :style="{ 'background-color': captchaColor.movColor, color:'#fff', 'z-index':9999, width:'20px', height:'20px',
                'text-align':'center', 'line-height':'20px', 'border-radius': '50%', position:'absolute',
                top:parseInt(tempPoint.y-10) + 'px',
                left:parseInt(tempPoint.x-10) + 'px' }">
                {{index + 1}}
              </div>
          </div>
        </div>
        <div slot="reference" class="verify-bar-area"
          :style="{'width': setSize.imgWidth, 'color': this.barAreaColor, 'border-color': this.barAreaBorderColor, 'line-height':this.barSize.height}">
          <span class="verify-msg">{{text}}</span>
        </div>
      </el-popover>
    </template>

    <template v-else>
      <div class="verify-img-out">
        <div class="verify-img-panel"
          :style="{'width': setSize.imgWidth, 'height': setSize.imgHeight, 'background-size' : setSize.imgWidth + ' '+ setSize.imgHeight, 'margin-bottom': '5px'}">
            <div class="verify-refresh" style="z-index:3" @click="refresh" v-show="showRefresh">
              <!-- iconfont icon-refresh  -->
              <i class="el-icon-refresh"></i>
            </div>
            <img :src="'data:image/png;base64,' + pointBackImgBase" ref="canvas" alt=""  style="width:100%;height:100%;display:block"
            @click="bindingClick?canvasClick($event):undefined" v-show="pointBackImgBase">

            <div v-for="(tempPoint, index) in tempPoints" :key="index" class="point-area"
              :style="{ 'background-color': captchaColor.movColor, color:'#fff', 'z-index':9999, width:'20px', height:'20px',
              'text-align':'center', 'line-height':'20px', 'border-radius': '50%', position:'absolute',
              top:parseInt(tempPoint.y-10) + 'px',
              left:parseInt(tempPoint.x-10) + 'px' }">
              {{index + 1}}
            </div>
        </div>
      </div>
      <div class="verify-bar-area"
        :style="{'width': setSize.imgWidth, 'color': this.barAreaColor, 'border-color': this.barAreaBorderColor, 'line-height':this.barSize.height}">
        <span class="verify-msg">{{text}}</span>
      </div>
    </template>
  </div>
</template>
<script>
import { resetSize } from './util'
import { aesEncrypt } from './ase'

export default {
  name: 'VerifyPoints',
  props: {
    captchaType:{
      type:String,
    },
    imgSize: {
      type: Object,
      default() {
        return {
          width: '310px',
          height: '155px',
          verifyFloat: false
        }
      }
    },
    barSize: {
      type: Object,
      default() {
        return {
          width: '310px',
          height: '40px'
        }
      }
    },
    captchaColor: {
      type: Object,
      default () {
        return {
          movColor: '#5cb85c',
          sucColor: '#0a77f5',
          errColor: '#d9534f'
        }
      }
    }
  },
  data() {
    return {
      popVisible:false,
      secretKey: '',           //后端返回的ase加密秘钥
      checkNum: 3,             //默认需要点击的字数
      fontPos: [],            //选中的坐标信息
      checkPosArr: [],        //用户点击的坐标
      num: 1,                 //点击的记数
      pointBackImgBase: '',    //后端获取到的背景图片
      poinTextList: [],        //后端返回的点击字体顺序
      backToken: '',           //后端返回的token值
      setSize: {
        imgHeight: 0,
        imgWidth: 0,
        barHeight: 0,
        barWidth: 0
      },
      tempPoints: [],
      text: '',
      barAreaColor: undefined,
      barAreaBorderColor: undefined,
      showRefresh: true,
      bindingClick: true
    }
  },
  computed: {
    resetSize() {
      return resetSize
    }
  },
  methods: {
    init () {
      //加载页面
      this.fontPos.splice(0, this.fontPos.length)
      this.checkPosArr.splice(0, this.checkPosArr.length)
      this.num = 1
      this.getPictrue()
      this.$nextTick(() => {
        this.setSize = this.resetSize(this)	//重新设置宽度高度
        this.$parent.$emit('ready', this)
      })
    },
    canvasClick (e) {
      this.checkPosArr.push(this.getMousePos(this.$refs.canvas, e));
      if (this.num == this.checkNum) {
        this.num = this.createPoint(this.getMousePos(this.$refs.canvas, e));
        //按比例转换坐标值
        this.checkPosArr = this.pointTransfrom(this.checkPosArr,this.setSize);
        //等创建坐标执行完
        setTimeout(() => {
          //发送后端请求
          var captchaVerification = this.backToken // this.secretKey? aesEncrypt(this.backToken+'---'+JSON.stringify(this.checkPosArr),this.secretKey):this.backToken+'---'+JSON.stringify(this.checkPosArr)
          let data = {
            type: this.captchaType,
            'pointJson': this.secretKey? aesEncrypt(JSON.stringify(this.checkPosArr),this.secretKey):JSON.stringify(this.checkPosArr),
            'captchaToken': this.backToken
          }
          // window.axios.post('https://mirror.anji-plus.com/captcha-api/captcha/check', data).then(resp => {
          // let hr = 'http://192.168.112.18:7003' // window.$twApp.gateway
          window.axios.post(window.$twApp.gateway + '/openapi-uc/captcha/checkCaptcha', data).then(resp => {
            // let res = resp.data
            let res = resp.data.responseEntity
            if (res.status) {
              this.barAreaColor = this.captchaColor.sucColor
              this.barAreaBorderColor = this.captchaColor.sucColor
              this.text = '验证成功'
              this.bindingClick = false

              this.$parent.$emit('success', {captchaVerification})
            } else {
              this.$parent.$emit('error', this)
              this.barAreaColor = this.captchaColor.errColor
              this.barAreaBorderColor = this.captchaColor.errColor
              this.text = '验证失败'
              setTimeout(() => {
                this.refresh()
              }, 700)
            }
          })
        }, 400)
      }
      if (this.num < this.checkNum) {
        this.num = this.createPoint(this.getMousePos(this.$refs.canvas, e))
      }
    },

    //获取坐标
    getMousePos: function (obj, e) {
      var x = e.offsetX
      var y = e.offsetY
      return {x, y}
    },
    //创建坐标点
    createPoint: function (pos) {
      this.tempPoints.push(Object.assign({}, pos))
      return ++this.num
    },
    refresh: function () {
      this.tempPoints.splice(0, this.tempPoints.length)
      this.barAreaColor = '#000'
      this.barAreaBorderColor = '#ddd'
      this.bindingClick = true
      this.fontPos.splice(0, this.fontPos.length)
      this.checkPosArr.splice(0, this.checkPosArr.length)
      this.num = 1
      this.getPictrue()
      this.text = '验证失败'
      this.showRefresh = true
    },

    // 请求背景图片和验证图片
    getPictrue(){
      let data = {
        captchaType:this.captchaType
      }
      // window.axios.post('https://mirror.anji-plus.com/captcha-api/captcha/get', data).then(resp => {
      // let hr = 'http://192.168.112.18:7003' // window.$twApp.gateway
      window.axios.get(window.$twApp.gateway + '/openapi-uc/captcha/getCaptcha?type=' + this.captchaType).then(resp => {
        // let res = resp.data
        // console.log('resp', resp)
        let res = resp.data.responseEntity
        if (resp.data.serverResult.resultCode == '200') {
        this.pointBackImgBase = res.originalImageBase64
        this.backToken = res.captchaToken
        this.secretKey = res.secretKey
        this.poinTextList = res.wordList
        this.text = '请依次点击【' + this.poinTextList.join(',') + '】'
        } else {
          this.tipWords = '获取验证码失败'
        }
        // if (res.repCode == '0000') {
        //   this.pointBackImgBase = res.repData.originalImageBase64
        //   this.backToken = res.repData.token
        //   this.secretKey = res.repData.secretKey
        //   this.poinTextList = res.repData.wordList
        //   this.text = '请依次点击【' + this.poinTextList.join(',') + '】'
        // }else{
        //   this.text = res.repMsg
        // }
      })
    },
    //坐标转换函数
    pointTransfrom(pointArr,imgSize){
      let newPointArr = pointArr.map(p=>{
        let x = Math.round(310 * p.x/parseInt(imgSize.imgWidth))
        let y =Math.round(155 * p.y/parseInt(imgSize.imgHeight))
        return {x,y}
      })
      // console.log(newPointArr,'newPointArr')
      return newPointArr
    }
  },
  mounted () {
    // 禁止拖拽
    this.init()
    this.$el.onselectstart = function () {
      return false
    }
  },
  watch: {
    popVisible: {
      immediate: true,
      handler (val) {
        if (val) {
          this.$nextTick(() => {
            let top = document.querySelector('.tw-login-verify-popper').style.top
            let left = document.querySelector('.tw-login-verify-popper').style.left
            document.querySelector('.tw-login-verify-popper').style.top = (parseInt(top) + 7) +'px'
            // document.querySelector('.tw-login-verify-popper').style.left = (parseInt(left) - 5) +'px'
            // console.log(top)
          })
        }
      }
    }
  }
}
</script>
